package code.c09;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/11/1 14:40
 * @package code.e09
 * @description 线程通信操作
 * 例子：线程交替打印 1-100
 */

public class Ex06 {
    public static void main(String[] args) {
        Number number = new Number();

        Thread thread1 = new Thread(number);
        Thread thread2 = new Thread(number);

        thread1.setName("线程1");
        thread2.setName("线程2");

        thread1.start();
        thread2.start();
    }
}

class Number implements Runnable {
    private int number = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                // notify 唤醒线程
                notify();

                if (number <= 100) {
                    System.out.println(Thread.currentThread().getName() + "-->" + number);
                    number++;
                    // 使得调用如下 wait 方法的线程进入阻塞状态
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }

    }
}